package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class JavaUtils {
    private static final long ExpireTime = 30*60*1000;
    private static final String secretString="dVnsmy+SIX6pNptQdeclDSJ26EMSPEIhvZYKBTTug4k=";  //密钥
    private static final SecretKey KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));   //通过


    public static String genJwt(Map<String, Object> claim) {
//签名算法
        String jwt = Jwts.builder()
                .setClaims(claim) //⾃定义内容(载荷)
                .setIssuedAt(new Date()) // 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() +
                        ExpireTime)) //设置过期时间
                .signWith(KEY) //签名算法
                .compact();
        return jwt;
    }
    public static Claims parseJWT(String jwt){
        if (!StringUtils.hasLength(jwt)){
            return null;
        }
//创建解析器, 设置签名密钥
        JwtParserBuilder jwtParserBuilder =
                Jwts.parserBuilder().setSigningKey(KEY);
        Claims claims = null;
        try {
//解析token
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e){
//签名验证失败
            log.error("解析令牌错误,jwt:{}",jwt);
        }
        return claims;
    }

    public static  Integer getUserIdFromToken(String jwtToken){
        Claims claims = JavaUtils.parseJWT(jwtToken);
        System.out.println("这是token取的值"+claims);
        if(claims!=null){
            Map<String,Object> userInfo = new HashMap<>(claims);
            return (Integer) userInfo.get("id");
        }
        return null;
    }

}
